﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace ClubWebsite
{
    public partial class PhotoGallery : System.Web.UI.UserControl
    {
        private int _photosPerPage = 0;
        private int _pageNumber = 1;
        private string _type;
        public string Type
        {
            get
            {
                return _type;
            }
            set
            {
                _type = value;
            }
        }
        private string _tags;
        public string Tags
        {
            get
            {
                return _tags;
            }
            set
            {
                _tags = value;
            }
        }
        private string _user;
        public string User
        {
            get
            {
                return _user;
            }
            set
            {
                _user = value;
            }
        }
        private string _gallery = "";
        public string Gallery
        {
            get
            {
                return _gallery;
            }
            set
            {
                _gallery = value;
            }
        }

        private bool _ignorePostbackCheck = false;
        public bool IgnorePostbackCheck
        {
            set
            {
                _ignorePostbackCheck = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            Page.RegisterRequiresControlState(this);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((!IsPostBack) || (_ignorePostbackCheck))
            {
                // Read the user's photo's per page setting
                if ((_photosPerPage == 0) && (Session["PhotosPerPage"] is int))
                {
                    _photosPerPage = (int)Session["PhotosPerPage"];
                }
                else
                {
                    _photosPerPage = 10;
                }

                DisplayPhotos();
            }
        }

        private void DisplayPhotos()
        {
            pnlPhotos.Controls.Clear();
            GalleryItem[] galleryItems;
            long totalNumberOfPhotos = 0;
            Func<IGallery> getGalleryInstance = () => 
            {
                switch (_type.ToLower())
                {
                    case "flickr":
                        return new FlickrGallery(ConfigurationManager.AppSettings["FlickrAPIKey"]);

                    case "picasa":
                        return new PicasaGallery(null);

                    default:
                        throw new NotSupportedException(String.Format("Type ({0}) is not supported.", _type));
                }
            };
            using (IGallery gallery = getGalleryInstance())
            {
                galleryItems = gallery.GetItems(_tags, _user, _pageNumber, _photosPerPage);
                if (galleryItems == null)
                {
                    return;
                }
                totalNumberOfPhotos = gallery.GetCount(_tags, _user);
            }
            System.Text.StringBuilder photoList = new System.Text.StringBuilder();
            foreach (GalleryItem galleryItem in galleryItems)
            {
                photoList.AppendLine("  <div class=\"photowrapper\">");
                photoList.AppendLine("    <a id='photo" + galleryItem.ID + "' href=\"" + galleryItem.URL + "\" class=\"highslide\" onclick=\"return hs.expand(this, { " + "captionId: 'caption" + galleryItem.ID + "'" + " " + _gallery + " } )\" target='_blank'><span></span><img src=\"" + galleryItem.ThumbnailURL + "\" alt=\"" + HttpUtility.HtmlEncode(galleryItem.Title) + "\" title=\"Click to enlarge\"/></a>");
                //photoList.AppendLine("    <div class='highslide-caption' id='caption" + photo.PhotoId + "'>" + HttpUtility.HtmlEncode(photo.Title) + "</div>");
                photoList.AppendLine("  </div>");
            }
            pnlPhotos.Controls.Add(new LiteralControl("<div class=\"images\">\r\n" + photoList.ToString() + "</div>"));

            // Set page controls
            if (_pageNumber <= 1)
            {
                btnPreviousPage.Visible = false;
            }
            else
            {
                btnPreviousPage.Visible = true;
            }
            decimal totalPages = Math.Ceiling((decimal)totalNumberOfPhotos / (decimal)_photosPerPage);
            if (_pageNumber >= totalPages)
            {
                btnNextPage.Visible = false;
            }
            else
            {
                btnNextPage.Visible = true;
            }
            ddlPage.Items.Clear();
            for (int pageNumber = 1; pageNumber <= totalPages; pageNumber++)
            {
                ddlPage.Items.Add(new ListItem(pageNumber.ToString(), pageNumber.ToString()));
            }
            ddlPage.Text = _pageNumber.ToString();
            litTotalPages.Text = totalPages.ToString();
            ddlPhotosPerPage.Items.Clear();
            ddlPhotosPerPage.Items.Add(new ListItem(10.ToString(), 10.ToString()));
            if ((totalNumberOfPhotos >= 25) || (_photosPerPage >= 25))
            {
                ddlPhotosPerPage.Items.Add(new ListItem(25.ToString(), 25.ToString()));
            }
            if ((totalNumberOfPhotos >= 50) || (_photosPerPage >= 50))
            {
                ddlPhotosPerPage.Items.Add(new ListItem(50.ToString(), 50.ToString()));
            }
            if ((totalNumberOfPhotos >= 100) || (_photosPerPage >= 100))
            {
                ddlPhotosPerPage.Items.Add(new ListItem(100.ToString(), 100.ToString()));
            }
            if ((totalNumberOfPhotos >= 500) || (_photosPerPage >= 500))
            {
                ddlPhotosPerPage.Items.Add(new ListItem(500.ToString(), 500.ToString()));
            }
            ddlPhotosPerPage.Text = _photosPerPage.ToString();
        }

        protected void btnPreviousPage_Click(object sender, EventArgs e)
        {
            if (_pageNumber > 1)
            {
                _pageNumber--;
            }
            DisplayPhotos();
        }

        protected void btnNextPage_Click(object sender, EventArgs e)
        {
            _pageNumber++;
            DisplayPhotos();
        }

        [Serializable()]
        private struct Properties
        {
            public int PhotosPerPage;
            public int PageNumber;
            public string Tags;
            public string User;
            public string Gallery;
            public Properties(int photosPerPage, int pageNumber, string tags, string user, string gallery)
            {
                PhotosPerPage = photosPerPage;
                PageNumber = pageNumber;
                Tags = tags;
                User = user;
                Gallery = gallery;
            }
        }

        protected override object SaveControlState()
        {
            return new Properties(_photosPerPage, _pageNumber, _tags, _user, Gallery);
        }

        protected override void LoadControlState(object state)
        {
            if (state is Properties)
            {
                _photosPerPage = ((Properties)state).PhotosPerPage;
                _pageNumber = ((Properties)state).PageNumber;
                _tags = ((Properties)state).Tags;
                _user = ((Properties)state).User;
                Gallery = ((Properties)state).Gallery;
            }
        }

        protected void ddlPhotosPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Display the new count of the photos per page
            _pageNumber = 1;
            _photosPerPage = int.Parse(ddlPhotosPerPage.SelectedValue);
            Session["PhotosPerPage"] = _photosPerPage;
            DisplayPhotos();
        }

        protected void ddlPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Go to the selected page number
            _pageNumber = int.Parse(ddlPage.SelectedValue);
            DisplayPhotos();
        }
    }
}